<template>
  <el-card v-loading="loading">
    <template #header>
      <div class="header">
        <el-icon class="icon" size="20" @click="goBack"><ArrowLeft /></el-icon>
        <span>问题录入</span>
      </div>
    </template>
    <div class="baseInfo">
      <div class="baseInfo-title">基本信息</div>
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="info">
            <div class="info-label">抽查计划</div>
            <div class="info-input">{{ detailInfo.planName || '' }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info">
            <div class="info-label">抽查事项</div>
            <div class="info-input">{{ detailInfo.itemNames || '' }}</div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="info">
            <div class="info-label">组织形式</div>
            <div class="info-input">{{ detailInfo.orgFrom || '' }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info">
            <div class="info-label">抽查对象</div>
            <div class="info-input">{{ detailInfo.objectName || '' }}</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="info">
            <div class="info-label">检查时间</div>
            <div class="info-input">
              {{
                getTime(detailInfo.spotCheckTime, detailInfo.spotCheckEndTime)
              }}
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="info">
            <div class="info-label">整改通知</div>
            <div class="info-input">
              <MUpload
                ref="uploadRef"
                list-type="text"
                :limit="1"
                v-model="files"
                @currentHttp="currentHttp"
                @onRemove="onRemove"
                v-if="$checkAuth('problemEntryNoticeOfRectification')"
              >
                <div class="info-input-file">
                  <el-button type="primary">上传文件</el-button>
                  <span>支持扩展名：docx .pdf .jpg.png...</span>
                </div>
              </MUpload>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <div class="search">
      <MForm
        :fields="fields"
        @submit="search"
        @cancel="search"
        submitIcon="icon-search"
        cancelIcon="icon-refreshLeft"
      ></MForm>
    </div>
    <div class="btns">
      <div class="btns-left">
        <el-button
          type="primary"
          @click="edit(0)"
          v-if="$checkAuth('problemEntryAdd')"
        >
          新增
        </el-button>
        <!--<div style="margin: 0 10px">-->
        <!--  <MDeleteButton-->
        <!--    @click="setInstitutionDel(selectKeys)"-->
        <!--    :selectKeys="selectKeys"-->
        <!--  ></MDeleteButton>-->
        <!--</div>-->
        <MImportData
          :http="problemImport"
          @reload="reload"
          :params="{ sorgSpotCheckId: route.query.id, types: detailInfo.types }"
          style="margin: 0 10px"
          v-if="$checkAuth('problemEntryUpload')"
        ></MImportData>
        <!--<el-button> 批量导入 </el-button>-->
        <el-button @click="download" v-if="$checkAuth('problemEntryDownLoad')">
          模板下载
        </el-button>
      </div>
      <div class="btns-rig">
        <!--<el-button v-if="$checkAuth('problemEntryCheckTheReport')">-->
        <!--  <template #icon>-->
        <!--    <img-->
        <!--      src="@/assets/imgs/spotCheck/icon/c4.svg"-->
        <!--      alt="icon"-->
        <!--      class="btn-icon"-->
        <!--    />-->
        <!--  </template>-->
        <!--  生成检查报告-->
        <!--</el-button>-->
        <el-button
          @click="generateLedgers"
          v-if="$checkAuth('problemEntryGenerateLedgers')"
        >
          <template #icon>
            <img
              src="@/assets/imgs/spotCheck/icon/c2.svg"
              alt="icon"
              class="btn-icon"
            />
          </template>
          生成台账
        </el-button>
        <!--<el-input-->
        <!--  v-model="params.search"-->
        <!--  placeholder="请输入问题描述"-->
        <!--  :suffix-icon="SearchIcon"-->
        <!--  style="margin-left: 15px"-->
        <!--/>-->
      </div>
    </div>
    <div class="content" v-loading="loadingTable">
      <div class="content-list" v-for="it in tableData">
        <div class="content-list-scroll">
          <div class="content-list-title">
            <TextTruncation :text="it.describes" />
          </div>
          <div class="content-list-item">
            <div class="content-list-item-label">问题类型</div>
            <div>
              <!--d:=>{{ it.types }}-->
              <TextTruncation :text="it.types" />
            </div>
          </div>
          <div class="content-list-item">
            <div class="content-list-item-label">整改要求</div>
            <div class="content-list-item-tx">
              <TextTruncation :text="it.requirement" />
            </div>
          </div>
        </div>
        <div class="content-list-footer">
          <div class="content-list-footer-left">
            <el-tag
              :type="it.rectifyFlag === 0 ? 'danger' : 'primary'"
              @click="it.rectifyFlag != 0 ? toPage(it.handleFlag === 1) : ''"
              >{{ it.rectifyFlag === 0 ? '未整改' : '已整改' }}</el-tag
            >
            <el-tag :type="it.confirmStatus === 0 ? 'warning' : 'primary'">{{
              it.confirmStatus === 0 ? '未确认' : '已确认'
            }}</el-tag>
            <el-tag type="primary" @click="previewFile(it)"
              >{{ it.fileNum || 0 }}份材料</el-tag
            >
          </div>
          <div class="list-header-rig">
            <MSvgIconTooltip
              name="view"
              content="查看"
              @click="toView(it.sorgProblemId)"
              v-if="$checkAuth('problemEntryView')"
            ></MSvgIconTooltip>
            <MSvgIconTooltip
              name="edit"
              content="编辑"
              :disabled="it.confirmStatus != 0"
              v-if="$checkAuth('problemEntryEdit')"
              @click="it.confirmStatus === 0 ? edit(it.sorgProblemId) : ''"
            ></MSvgIconTooltip>
            <MSvgIconTooltip
              name="del"
              content="删除"
              v-if="$checkAuth('problemEntryDel')"
              :disabled="it.confirmStatus != 0"
              @click="
                it.confirmStatus === 0
                  ? setInstitutionDel([it.sorgProblemId])
                  : ''
              "
            ></MSvgIconTooltip>
            <MSvgIconTooltip
              name="handOver"
              content="转入协同治理"
              v-if="$checkAuth('problemEntryINTO')"
              :disabled="it.handleFlag === 1"
              @click="
                it.handleFlag === 1 ? '' : transitionToSynergy(it.sorgProblemId)
              "
            ></MSvgIconTooltip>
            <MSvgIconTooltip
              name="sure"
              content="确定"
              v-if="$checkAuth('problemEntrySure')"
              :disabled="it.confirmStatus != 0"
              @click="it.confirmStatus === 0 ? sure(it.sorgProblemId) : ''"
            ></MSvgIconTooltip>
          </div>
        </div>
      </div>
    </div>
    <div class="m-table__pagination">
      <div class="m-table__pagination__total">
        共 {{ dataTotal }} 条记录 第 {{ params.pageNum }} /
        {{ Math.ceil(dataTotal / params.pageSize) }} 页
      </div>
      <el-pagination
        background
        layout="prev, pager, next, sizes, jumper"
        v-model:currentPage="params.pageNum"
        v-model:page-size="params.pageSize"
        :total="dataTotal"
        @size-change="handleSizeChange"
      >
      </el-pagination>
    </div>
  </el-card>
  <MFormDialog
    v-model="formDialog.visible"
    v-bind="formDialog"
    :value="formData"
    :fields="dialogFields"
    @reload="reload"
    :httpAdd="problemAddOrUpd"
    :httpEdit="problemEditOrUpd"
    :httpGet="problemDetailIdHttp"
    :handler="handlerSubmit"
    addTitle="新增问题"
    editTitle="编辑问题"
    :width="1200"
  ></MFormDialog>
  <!--预览-->
  <MFileList ref="mfileList" :fileData="fileData" />
</template>

<script setup lang="ts">
import { ArrowLeft } from '@element-plus/icons-vue'
import { Search as SearchIcon } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router'
import { fields, dialogFields } from './config'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import {
  problemRectify,
  soptCheckDetail,
  problemAddOrUpd,
  getManagerChild,
  problemPage,
  problemDel,
  problemDownloadExcelTemplate,
  soptCheckLedger,
  problemImport,
  problemLedger,
  problemConfirm,
  problemChange,
  problemDetailId,
  problemEditOrUpd,
  problemNoRectigy,
  riskTypeSortRisk,
  riskTypeSortProblem
} from '@/api/spotCheck/spotCheck'
import { contentFieldsRelevancy } from '@/views/dataUse/systemSetLayout/paramsManagement/config'
import { ElMessage, ElMessageBox } from 'element-plus'
import TextTruncation from '../../components/textTruncation/textTruncation.vue'
import { dateFormat } from '@/utils'

const router = useRouter()
const route = useRoute()
const files: any = ref([])
defineOptions({
  name: 'ProblemEntry'
})

//预览
const mfileList = ref()
const fileData = ref([])
function previewFile(it) {
  let fileDataList = it.files.map((i) => ({
    name: i.fileName,
    url: i.fileUrl
  }))

  fileData.value = fileDataList
  mfileList.value.detailsVisible = true
}

const formData = ref({
  files: []
})

const getTime = (n, m) => {
  if (n && m) {
    return n + '至' + m
  } else if (n) {
    return n
  } else if (m) {
    return m
  } else {
    return ''
  }
}
const detailInfo = ref('')
const loading = ref(false)
onMounted(() => {
  loading.value = true
  soptCheckDetail(route.query.id)
    .then((res: any) => {
      detailInfo.value = res.data
      if (res.data?.noticeFile) {
        files.value = [
          {
            status: 'success',
            name: res.data.noticeFileName,
            url: res.data.noticeFile
          }
        ]
      }
      // 0 民办非企业 riskMingBan 1 社会团体 riskSheTuan
      let types = res.data.types === 0 ? 'riskMingBan' : 'riskSheTuan'
      //问题类型
      getManagerChild(types).then((res) => {
        dialogFields.value.find((i) => i.key === 'types').attrs.options =
          res.data.map((i) => ({
            value: i.name,
            label: i.name,
            relationParameterName: i.relationParameterName
          }))
        // fields.value.find((i) => i.key === 'types').attrs.options =
        //   res.data.map((i) => ({
        //     value: i.name,
        //     label: i.name
        //   }))
      })

      riskTypeSortProblem(res.data.types).then((res) => {
        fields.value.find((i) => i.key === 'types').attrs.options =
          res.data.map((i) => ({
            value: i.name,
            label: i.name
          }))
      })
      reload()
    })
    .finally(() => {
      loading.value = false
    })
})

const toPage = () => {
  console.log('跳转')
}

const onRemove = (e) => {
  console.log('删除', e)
  // let data = {
  //   fileName: null,
  //   fileUrl: null,
  //   sorgSpotCheckId: route.query.id
  // }
  // problemRectify(data)
  problemNoRectigy({ sorgSpotCheckId: route.query.id })
}

//上传传
const currentHttp = (val) => {
  console.log('currentHttp', val)
  let data = {
    fileName: val.name,
    fileUrl: val.url,
    sorgSpotCheckId: route.query.id
  }
  problemRectify(data)
}

// 新增/编辑
const formDialog = reactive({
  visible: false,
  id: 0
})
const edit = (id: number) => {
  formDialog.id = id
  formDialog.visible = true
}

const handlerSubmit = (e) => {
  console.log('e', e)
  let files = []
  let riskLevel = ''
  try {
    files = e.files
      .filter((i) => i.isSave)
      .map((i) => {
        let file = {
          fileName: '',
          filePage: i.fileSum,
          fileUrl: ''
        }
        if (Array.isArray(i.file) && i.file.length > 0) {
          //上传了文件
          file.fileName = i.name
          file.fileUrl = i.file[0].url
        }
        return file
      })
  } catch (e) {
    /* empty */
  }
  try {
    riskLevel = dialogFields.value
      .find((i) => i.key === 'types')
      .attrs.options.find((i) => e.types === i.label).relationParameterName
  } catch (e) {}
  e = {
    riskHandleFlag: 0,
    status: route.query.status, //分类 0抽查 1检查
    sorgSpotCheckId: route.query.id,
    orgName: detailInfo.value.objectName,
    ...e,
    riskLevel,
    files
  }
  return e
}

//返回
const goBack = () => {
  router.go(-1)
}

// 搜索
const search = (data: any) => {
  params.value = {
    ...params.value,
    ...data
  }
  reload()
}

/*
分页
 */
const dataTotal = ref(0)
const params: any = ref({
  pageNum: 1,
  pageSize: 20,
  sorgSpotCheckId: route.query.id
})

function handleSizeChange(e) {
  params.value.pageNum = 1
  params.value.pageSize = e
  init()
}

function currentChange(e) {
  params.value.pageNum = e
  init()
}

const loadingTable = ref(false)
const tableData = ref([])
const init = () => {
  loadingTable.value = true
  problemPage(params.value)
    .then((res) => {
      tableData.value = res.data.records
      dataTotal.value = res.data.total
    })
    .finally(() => {
      loadingTable.value = false
    })
}

const reload = () => {
  params.value.pageNum = 1
  init()
}

const toView = (id) => {
  router.push({
    name: 'spotCheckProblemEntryView',
    query: {
      id,
      status: route.query.status
    }
  })
}

//选中id
const selectKeys = computed(() => {
  return tableData.value.filter((i) => i.checked).map((i) => i.sorgSpotCheckId)
})

//批量删除
const setInstitutionDel = (e) => {
  problemDel({ sorgProblemId: e }).then((res) => {
    ElMessage.success('删除成功！')
    reload()
  })
}

//下载模板
const download = () => {
  problemDownloadExcelTemplate({ types: detailInfo.value.types }).then(
    (res) => {
      const blob = new Blob([res], {
        type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      })
      const a = document.createElement('a')
      const URL = window.URL || window.webkitURL
      const herf = URL.createObjectURL(blob)
      a.href = herf
      a.download = '模板.xlsx'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(herf)
    }
  )
}

//生成台账
const generateLedgers = () => {
  problemLedger({ sorgSpotCheckId: route.query.id }).then((res) => {
    const blob = new Blob([res], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    const a = document.createElement('a')
    const URL = window.URL || window.webkitURL
    const herf = URL.createObjectURL(blob)
    a.href = herf
    a.download = '台账.xlsx'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(herf)
  })
}

//确定
const sure = (id) => {
  ElMessageBox.confirm('是否进行确认？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      problemConfirm({ sorgProblemId: id, status: route.query.status }).then(
        (res) => {
          reload()
        }
      )
    })
    .catch(() => {})
}

const transitionToSynergy = (id) => {
  ElMessageBox.confirm('请确认是否转入协同治理？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      problemChange({ sorgProblemId: id, status: route.query.status }).then(
        (res) => {
          reload()
        }
      )
    })
    .catch(() => {})
}

const problemDetailIdHttp = async (id) => {
  const res = await problemDetailId(id)
  if (Array.isArray(res.data.files) && res.data.files.length > 0) {
    res.data.files = res.data.files.map((i) => ({
      fileSum: i.filePage,
      isSave: true,
      name: i.fileName,
      createdAt: dateFormat(i.createdAt, 'YYYY-MM-DD'),
      file: [
        {
          name: i.fileName,
          status: 'success',
          url: i.fileUrl
        }
      ]
    }))
  } else {
    res.data.files = []
  }

  return res
}
</script>

<style scoped lang="scss">
.header {
  display: flex;
  align-items: center;
  .icon {
    margin-right: 16px;
    cursor: pointer;
  }
  span {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 500;
    font-size: 20px;
    color: #333333;
  }
}
.baseInfo {
  width: 100%;
  border-radius: 0px 0px 0px 0px;
  border: 1px solid #e9e9e9;
  box-sizing: border-box;
  padding: 20px 30px;
  padding-bottom: 0;
  .baseInfo-title {
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 500;
    font-size: 20px;
    color: #333333;
    position: relative;
    padding-left: 12px;
    margin-bottom: 20px;
  }
  .baseInfo-title::before {
    content: '';
    width: 4px;
    height: 20px;
    background: #1c85ff;
    position: absolute;
    left: 0;
    top: 0;
  }
}
.info {
  display: flex;
  margin-bottom: 20px;
  .info-label {
    height: 27px;
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 300;
    font-size: 18px;
    color: #666666;
    margin-right: 20px;
    display: inline-flex;
    align-items: center;
  }
  .info-input {
    flex: 1;
    font-family: Source Han Sans SC, Source Han Sans SC;
    font-weight: 400;
    font-size: 18px;
    color: #333333;
    line-height: 30px;
    min-width: 0;
  }
}
.info-input-file {
  span {
    font-weight: 300;
    font-size: 14px;
    color: #666666;
    line-height: 0px;
    margin-left: 10px;
    padding-top: 10px;
  }
}
.search {
  padding: 20px 0 12px;
}
.btns {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  &-left {
    display: flex;
    align-items: center;
  }
  .btns-rig {
    display: flex;
    align-items: center;
  }
}
.content {
  width: 100%;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 20px;
  .content-list {
    width: 100%;
    border: 1px solid #e9e9e9;
    .content-list-scroll {
      width: 100%;
      padding: 30px;
      padding-bottom: 0;
      box-sizing: border-box;
    }
  }
  .content-list-title {
    font-weight: bold;
    font-size: 18px;
    color: #333333;
    margin-bottom: 20px;
  }
  .content-list-item {
    display: flex;
    margin-bottom: 20px;
    .content-list-item-label {
      font-weight: 400;
      font-size: 18px;
      color: #999999;
      margin-right: 20px;
    }
    .content-list-item-tx {
      flex: 1;
      font-weight: 400;
      font-size: 18px;
      color: #666666;
    }
  }
  .content-list-footer {
    width: 100%;
    display: flex;
    height: 50px;
    align-items: center;
    justify-content: space-between;
    box-sizing: border-box;
    padding: 0 30px;
    border-top: 1px solid #e9e9e9;
    .content-list-footer-left {
      & > span {
        margin-right: 20px;
      }
    }
    .list-header-rig {
    }
  }
}
.list-header-rig {
  display: flex;
  .list-header-rig-btn {
    font-weight: 300;
    font-size: 16px;
    color: #333333;
    padding: 0 21px;
    position: relative;
    cursor: pointer;
  }
  .list-header-rig-btn::after {
    content: '';
    width: 0;
    height: 20px;
    border: 1px solid #e9e9e9;
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    margin: auto;
  }
  .list-header-rig-btn:last-child {
    padding-right: 0;
  }
  .list-header-rig-btn:last-child::after {
    height: 0;
  }
}
.m-table__pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30px 30px 0px 30px;
  box-sizing: border-box;
  &__total {
    color: #0000006d;
  }
}

.disabled {
  opacity: 0.6; /* 半透明 */
  cursor: not-allowed !important; /* 禁用光标 */
}
</style>
